# -*- coding: utf-8 -*-
from datetime import datetime
import maya.mel as mel
import maya.cmds as cmds
import subprocess
import re
import os
import tempfile
import shutil
import getpass
import ctypes
'''
temp_folder = tempfile.gettempdir()

type = "png"
scenepath = cmds.file(q=1,sn=1)


scenepathsp = scenepath.split('/')
scenename = scenepathsp[-1].split('.')[0]
playblastTemp_folder =  os.path.join(temp_folder,scenename).replace("\\", "/")
outputPath_Directory   = os.path.join(os.path.dirname(scenepath),scenename + ".mov").replace("\\", "/")
'''
#print(outputPath_Directory)
#outputTempPath = os.path.join(playblastTemp_folder,scenename + ".mov").replace("\\", "/")
class Playblast():
	def create_ass(self,outputPath_Directory,playblastTemp_folder,scenename,type,width,height):

		
		#width = cmds.getAttr("defaultResolution.w")
		#height = cmds.getAttr("defaultResolution.h")
		
		time_fps = cmds.currentUnit(q=1, t=1)
		if time_fps == 'game':
			fps = 15
		elif time_fps == 'film':
			fps = 24
		elif time_fps == 'pal':
			fps = 25
		elif time_fps == 'ntsc':
			fps = 30
		elif time_fps == 'show':
			fps = 48
		elif time_fps == 'palf':
			fps = 50
		elif time_fps == 'ntscf':
			fps = 60

		i= 1920
		Fontsize = 40*(width /i)
		Fontname = "\u9ed1\u4f53"  #"Adobe Arabic"
		PrimaryColour= "&H0000FFFF"#	"&H00FFF8F8"   黄色"&H00FFFF00"  白色"&H00FFFAFA"
		SecondaryColour= "&H00FFFFFF"  #   &HFFFF0000 "&H00DC143C"
		OutlineColour= "&HFFFFFFFF"  #"&H0000FFFF"
		BackColour= "&H00000000"
		BorderStyle = 1
		Outline = 0
		Shadow = 0
		
		#assPath ="D:/wwwww/test_hud.ass"
		assPath = os.path.join(playblastTemp_folder, scenename + ".ass").replace("\\", "/")
		#exportpath = "D:/wwwww/eeeeee"
		exportpath = os.path.join(playblastTemp_folder, scenename).replace("\\", "/")
		#inP = "-i " + "D:/wwwww/eeeeee.%04d.png"
		inP = "-i " + exportpath + ".%04d.png"
		ffexe ="H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"
		
		cmds.setAttr('hardwareRenderingGlobals.gammaValue ', 5)
		list_headsUpDisplay = cmds.headsUpDisplay (listHeadsUpDisplays = 1)
		if list_headsUpDisplay:
			for i in list_headsUpDisplay:
				cmds.headsUpDisplay(i, remove=True)
		cmds.playblast(format='image',filename = exportpath ,sequenceTime=0,clearCache=1,viewer=0,showOrnaments=1,fp=4,percent=100,compression=type,quality=100,widthHeight=(width,height))
		
		Hud_ASS = ''
		Hud_ASS += "[Script Info]\n"	
		Hud_ASS += "ScriptType: v4.00\n"	
		Hud_ASS += "PlayResX: " + str(width)+"\n"	
		Hud_ASS += "PlayResY: " + str(height)+"\n"	
		Hud_ASS += "WrapStyle: 0\n"	
		Hud_ASS += "[V4+ Styles]\n"	
		Hud_ASS += "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"	 				
		Hud_ASS += u"Style: ProjSize,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},8,0,0,5,134\n".format(str(Fontname), str(Fontsize), str(PrimaryColour) , str(SecondaryColour) , str(OutlineColour),str(BackColour), str(BorderStyle) ,str(Outline),str(Shadow))					  
		Hud_ASS += u"Style: Date,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},7,10,0,5,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))		   
		Hud_ASS += u"Style: FocalLength_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},9,0,10,10,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))	 
		Hud_ASS += u"Style: FileCam_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},9,0,10,5,134\n".format( str(Fontname) , str(Fontsize) , str(PrimaryColour) , str(SecondaryColour) , str(OutlineColour), str(BackColour) , str(BorderStyle) , str(Outline) , str(Shadow))	
		Hud_ASS += u"Style: User,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},1,10,0,5,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))	
		Hud_ASS += u"Style: PCName,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},1,10,0,10,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))	
		Hud_ASS += u"Style: Scene_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},2,0,0,5,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))	
		Hud_ASS += u"Style: TimeCode,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},3,0,10,5,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))	
		Hud_ASS += u"Style: Frame_text,{},{},{},{},{},{},-1,0,0,0,60,60,0,0,{},{},{},3,0,10,10,134\n".format(str(Fontname),str(Fontsize),str(PrimaryColour),str(SecondaryColour),str(OutlineColour),str(BackColour),str(BorderStyle),str(Outline),str(Shadow))

		Hud_ASS += "\n"																																		  	
		Hud_ASS += "[Events]\n"
		
		increase_value= round((100 / float(fps)),0)
		MinTimes=int(cmds.playbackOptions( q=1, minTime=1))
		MaxTimes= int(cmds.playbackOptions( q =1,maxTime=1))
		File_sceneName = cmds.file(q=1, sceneName=1, shortName=1)
		
		PCName = os.environ.get ("COMPUTERNAME")
		hud_resolution = str (cmds.getAttr ("defaultResolution.width")) + " x " + str (cmds.getAttr ("defaultResolution.height"))
					
		frameRate = int(MaxTimes + 1 - MinTimes)
		
		all_camera = [ i for i in cmds.listCameras(p=1) if i != 'persp' ]
		obj_list = []
		playblastCame=''
		for i in all_camera:
			if not cmds.referenceQuery(i, isNodeReferenced=True):
				obj_list.append(i)
				playblastCame = obj_list[0]
		if cmds.listRelatives(playblastCame,p=1):
			CameraShape = playblastCame
			print("1")
		else:
			CameraShape = cmds.listRelatives(playblastCame,shapes=1)[0]
			print("2")
		'''
		cmds.setAttr ( CameraShape + ".horizontalFilmAperture"	, 2.2582677165399998)
		cmds.setAttr ( CameraShape + ".verticalFilmAperture"	, 0.944881889764 )
		#cmds.setAttr ( CameraShape + ".horizontalFilmAperture"	, l= 1) 
		#cmds.setAttr ( CameraShape + ".verticalFilmAperture"	, l= 1) 
		'''
		now = datetime.now()
		time = now.strftime('%Y/%m/%d %H:%M:%S')
		
		for i in range(frameRate):
			#time = datetime.datetime.now ().strftime ('%Y/%m/%d %H:%M:%S')
			
			current_ms = str(((i)%fps)).zfill(1)
			#print(current_ms)
			current_sencond = str((i+1)/fps).split(".")[0]
			current_timeconde = current_sencond + ":" + current_ms
			#print(current_timeconde)
			CameFocalLength = cmds.getAttr (CameraShape + ".focalLength",time= MinTimes + i)
			Hud_ASS += self.wirte_ass_file(i,increase_value,playblastCame,hud_resolution,CameFocalLength,PCName,time,File_sceneName,current_timeconde,fps,MinTimes,MaxTimes)
		
		Hud_ASS = Hud_ASS.encode('utf-8')
		with open(assPath, 'w') as f:
			f.write(Hud_ASS)
			f.close()
		'''
		with open(assPath, 'w') as file:
			file.write(Hud_ASS)
			file.close()'''
	
		audioOffset = 0
		audioFileCmd = ''
		AudioList= []
		
		Audios = cmds.ls(type = "audio")
		print(Audios)
		print("----------------------------------------------------------------------------")
		aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')

		PlayBlastAudio = cmds.timeControl(aPlayBackSliderPython, q=1, s=1)
		if PlayBlastAudio:
			AudioList.append(PlayBlastAudio)
		if len(Audios)==1:
			if len(AudioList)==1:
				Audio = AudioList[0]
				audioOffset = int(cmds.getAttr(Audio + ".offset") - MinTimes)
				audioFile = cmds.sound(Audio, q=1, file=1)
			else:
				Audio  = Audios[0]
				audioOffset = int(cmds.getAttr(Audio + ".offset") - MinTimes)
				audioFile = cmds.sound(Audio, q=1, file=1)
			
			if not self.is_ascii(audioFile):
				print(u"音频路径存在中文")
				pass

			offsetSec = float(audioOffset) / float(fps)
			print (offsetSec)
			offsetCmd = ''
			if audioOffset > 0:
				offsetCmd += "-itsoffset " + str(offsetSec) + " "
			else:
				offsetCmd += "-ss " + str(abs(offsetSec)) + " "
			print (offsetCmd)
			if len(audioFile) or os.path.exists(audioFile):#mel.eval('filetest - e audioFile')
				audioFileCmd = offsetCmd + "-i " + audioFile
			
			if not os.path.isfile(audioFile):
				audioFileCmd = ''
				print (audioFileCmd)
		timeRange = "-t " + str((MaxTimes - MinTimes + 1)/float(fps))
		s = " "
		start = "-start_number" + " " + str(MinTimes)
		
		#inP = "-i " + "D:/cam_0100.mov"
		#assP = "-vf subtitles=" "\\\'" + assPath + "\\\'"
		#assPath.replace()
		converted_path =assPath.replace("/","\\\\")
		converted_path = converted_path.replace(":", "\\:")
		assPaths =assPath.split("/")
		assP = ("-vf subtitles=" "\\\'" + converted_path + "\\\'")
		#assP = "-vf subtitles=" "\\'D\\:\\test_hud.ass\\'"
		outP = "-c:v libx264 -b 18000k -pix_fmt yuv420p -crf 1 -y " + outputPath_Directory
		hudInfo = [start,inP,audioFileCmd,timeRange,assP,outP]
		#hudInfo = [start,inP,assP,outP]
		command_line = ffexe + " " + s.join(hudInfo)
		#subprocess.Popen(command_line)
		os.popen(command_line)
		#shutil.copy(outputTempPath, outputPath_Directory)
		#for i in os.listdir(playblastTemp_folder):
		#	os.remove(playblastTemp_folder +"/"+ i)
		os.startfile(outputPath_Directory)	
		shutil.rmtree(playblastTemp_folder)	
		
	def write_output_window(self,s):
		u"""\u5199\u5165maya\u7684OutPutWindow"""
		if isinstance(s, unicode):
			s = s.encode('gbk')
			sys.__stdout__.write('{}\n'.format(s))
		elif isinstance(s, str):
			s = s.decode('utf-8').encode('gbk')
			sys.__stdout__.write('{}\n'.format(s))
		else:
			return False
	def week_day(self):	
		now = datetime.now()
		week = [u"星期一", u"星期二", u"星期三", u"星期四", u"星期五", u"星期六", u"星期日"]
		week_day = week[now.weekday()]
		#utf8_week_day = week_day.encode('utf-8')
		time = now.strftime('%Y/%m/%d %H:%M:%S')
		return (week_day)
	def is_ascii(self,string):
		for char in string:
			if ord(char) > 127:
				return False
		return True
	def getDisplayName(self):
		GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
		NameDisplay = 3
		size = ctypes.pointer(ctypes.c_ulong(0))
		GetUserNameEx(NameDisplay, None, size)
		nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
		GetUserNameEx(NameDisplay, nameBuffer, size)
		computerName = os.popen('hostname').read()
		return (nameBuffer.value)
	def getpass(self):
		username = getpass.getuser()
		return(username)
	def wirte_ass_file(self,i,increase_value,playblastCame,hud_resolution,CameFocalLength,PCName,time,File_sceneName,current_timeconde,fps,MinTimes,MaxTimes):
		Hud_ASS = ''
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"Frame_text", str(MinTimes)  + "/" + str(MinTimes + i) + "/" + str(MaxTimes))
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"FileCam_text", str(playblastCame))
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"ProjSize", hud_resolution)
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"FocalLength_text", str(CameFocalLength))
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"User", self.getDisplayName())#.encode("UTF-8")
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"PCName", str(PCName))
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"Date",  str(time) + self.week_day())
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"Scene_text", str(File_sceneName))
		Hud_ASS += u"Dialogue: 0,0:00:00.{},0:00:00.{},{},,0,0,0,,{}\n".format( str(round(i * increase_value ,0)),str(round(i * increase_value + increase_value ,0)) ,"TimeCode", current_timeconde + "(" + str(fps) + "fps)")
		
		return (Hud_ASS)
#Playblast().create_ass(outputPath_Directory,playblastTemp_folder,scenename,type)